<template>
  <div class="main-lineSearch">
    <div class="layui-tab layui-tab-brief" lay-filter="test-handle">
      <ul class="layui-tab-title">
        <li class="layui-this" lay-id="search">查询</li>
        <li lay-id="result">显示结果</li>
      </ul>
      <div class="layui-tab-content">
        <div class="layui-tab-item layui-show">
          <div style="display:flex; padding: 15px 0; border-bottom: 1px solid #fff;">
            <div style="width:33%; text-align: center; ">
              <label class="btn btn-primary" style="margin: 3px 0; ">
                <input class="guanline-search-type" type="checkbox" value="ZY_JSLINE"> 给水线
              </label>
              <br/>
              <label class="btn btn-primary" style="margin: 3px 0; ">
                <input class="guanline-search-type" type="checkbox" value="ZY_YSLINE"> 雨水线
              </label>
              <br/>
              <label class="btn btn-primary" style="margin: 3px 0; ">
                <input class="guanline-search-type" type="checkbox" value="ZY_GDLINE"> 电力线
              </label>
              <br/>
              <label class="btn btn-primary" style="margin: 3px 0; ">
                <input class="guanline-search-type" type="checkbox" value="ZY_LDLINE"> 路灯线
              </label>
            </div>
            <div style="width:33%; text-align: center; ">
              <button type="button" class="layui-btn layui-btn-sm layui-btn-normal" style="margin: 3px 0; width: 80px;"
                      @click="allSelect(1)">全选
              </button>
              <br/>
              <button type="button" class="layui-btn layui-btn-sm layui-btn-normal" style="margin: 3px 0; width: 80px;"
                      @click="allSelect(-1)">全不选
              </button>
              <br/>
              <button type="button" class="layui-btn layui-btn-sm layui-btn-normal" style="margin: 3px 0; width: 80px;"
                      @click="allSelect(0)">反选
              </button>
            </div>
          </div>
          <div class="layui-row" style="padding: 15px 0; border-bottom: 1px solid #fff;">
            <div class="layui-col-md6 layui-col-md-offset1">
              <input type="button" class="btn btn-primary" value="矩形" @click="drawRectangle"/>
              <input type="button" class="btn btn-primary" value="面" @click="drawPolygon"/>
              <input type="button" class="btn btn-primary" value="圆" @click="drawCircle"/>
              <input type="button" class="btn btn-primary" value="清除" @click="clearDraw"/>
            </div>
          </div>
        </div>
        <div class="layui-tab-item">
          <!-- <div style="">
              选择管线：
              <select id="layerSelect" style="width:200px; height:30px;  color:black;">
                  <option style="color:#000"></option>
              </select>
          </div> -->
          <table
              id="table"
              data-toggle="table"
              data-height="550"
              data-width="430"
              data-search="true"
              data-pagination="true"
              style="overflow: hidden;text-overflow: ellipsis;white-space: nowrap; color:#fff;"
          >
            <thead id="thead" style="color:#fff;">

            </thead>
          </table>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
// eslint-disable-next-line no-unused-vars
let from
// eslint-disable-next-line no-unused-vars
let count
// eslint-disable-next-line no-unused-vars
let dataTable = []
let selectEntity = []
let $table
import layersMap from "@/components/js/layerMap";
import fetchData from "@/components/js/fetchData";
import {highLightForLineSearch} from "@/components/js/highLight";

export default {
  name: "lineSearch",
  components: {},
  data() {
    return {};
  },
  mounted() {
    $table = $('#table');
  },
  methods: {
    allSelect(flag) {
      let els = $('.guanline-search-type')
      if (flag == 1) {
        for (let index = 0; index < els.length; index++) {
          const element = els[index];
          element.checked = true
        }
      } else if (flag == -1) {
        $('.guanline-search-type').attr('checked', false)
      } else { // 反选
        for (let index = 0; index < els.length; index++) {
          const element = els[index];
          element.checked = !element.checked
        }
      }
    },
    updateSelect() {
      // 拿到绘制的geojson
      let drawGeojson = window.viewer.dadi.draw.toGeoJSON()

      let els = $('.guanline-search-type')
      let pipelineTypes = []
      for (let index = 0; index < els.length; index++) {
        const element = els[index];
        if (element.checked) {
          pipelineTypes.push(element.value)
        }
      }

      if (pipelineTypes.length == 0) {
        layui.layer.alert('至少选择一类管点进行查询！')
        setTimeout(() => {
          $('.layui-layer-dialog[type="dialog"]').css('height', 'unset')
        }, 100);
        return;
      }

      if (drawGeojson.features[0].properties.type === 'circle') {
        from = turf.buffer(turf.feature(drawGeojson.features[0].geometry), Number(drawGeojson.features[0].properties.style.radius) / 1000, {units: 'kilometers'})
      } else if (drawGeojson.features[0].properties.type === 'polygon') {
        from = turf.feature(drawGeojson.features[0].geometry)
      } else if (drawGeojson.features[0].properties.type === 'rectangle') {
        let geo = drawGeojson.features[0].geometry.coordinates.reduce(function (a, b) {
          a.splice(-1)
          b.splice(-1)
          return a.concat(b)
        })
        from = turf.bboxPolygon(geo)
      }
      let features = [], properties = [];
      let count = 0;
      // eslint-disable-next-line no-unused-vars
      layersMap.forEach(async (item, index) => {
        let _layer = Object.values(window.viewer.dadi.layers).find(l => l.config.id === item.id)
        if (_layer?._visible) {
          const r = await fetchData(item.url)
          // 求交集
          r.features.forEach(fea => {
            let to = turf.feature(fea.geometry)
            let withIntersect = turf.booleanIntersects(to, from);
            if (withIntersect) {
              features.push(fea)
              properties.push({ ...fea.properties , configLayerId: _layer.config.id})
            }
          })
        }
        count++
      })

      let timer = setInterval(() => {

        if (count === layersMap.length) {
          window.clearInterval(timer)
          count = 0;

          let thead = `<tr>`
          Object.keys(properties[0]).forEach(key => {
            thead += `<th data-field="${key}">${key}</th>`
          })
          thead += `</tr>`
          $table.bootstrapTable('destroy')
          $('#thead').html(thead)
          dataTable = properties;
          $table.bootstrapTable({
            data: properties,
            // eslint-disable-next-line no-unused-vars
            onClickRow: function (row, $element) {
              highLightForLineSearch(row)
            }
          })
        }
      }, 2000);

      layui.element.tabChange('test-handle', 'result'); // 切换到：标签3
    },
    hideLayerContent() {
      this.$emit('hidden')
    },
    showLayerContent() {
      this.$emit('show')
    },
    clearDraw() {
      window.window.viewer.dadi.draw.clearDraw();
      for (var i = 0; i < selectEntity.length; i++) {
        selectEntity[i].billboard.image = 'img/marker/mark3.png';
      }
      selectEntity = [];
      from = null;
      // $table.bootstrapTable('destroy')
      $('#layerSelect').html('');
      // $('#thead').html('')
      dataTable = []
    },
    drawRectangle() {
      this.clearDraw();
      this.hideLayerContent();
      window.window.viewer.dadi.draw.startDraw({
        type: "rectangle",
        style: {
          color: "#ffff00",
          opacity: 0.2,
          clampToGround: true,
        },
        success: (entity) => {
          count = 0;
          this.updateSelect(entity);
          this.showLayerContent();
        }
      });
    },
    drawPolygon() {
      this.clearDraw();
      this.hideLayerContent();
      window.viewer.dadi.draw.startDraw({
        type: "polygon",
        style: {
          color: "#ffff00",
          opacity: 0.2,
          clampToGround: true,
        },
        success: (entity) => {
          count = 0
          this.updateSelect(entity);
          this.showLayerContent();
        }
      });
    },
    drawCircle() {
      this.clearDraw();
      this.hideLayerContent();
      window.viewer.dadi.draw.startDraw({
        type: "circle",
        style: {
          color: "#ffff00",
          opacity: 0.2,
          clampToGround: true,
        },
        success: (entity) => {
          count = 0;
          this.updateSelect(entity);
          this.showLayerContent();
        }
      });
    },
  },
  watch: {},
  computed: {},
  beforeDestroy() {
    this.clearDraw()
    let highLightLayer = window.viewer.dataSources.getByName('highLightLayer')[0]
    if (highLightLayer) {
      highLightLayer.entities.removeAll()
    }
  },
}
</script>

<style scoped>
.main-lineSearch {
  position: relative;
  height: 100%;
  width: 100%;
  color: white;
  font-size: 14px;
}

.searchGroup {
  width: 45%;
  padding: 5px;
  display: flex;
  align-items: center;
}

.searchGroup > div {
  line-height: 32px;
}

.searchGroup input {
  margin: 0 5px;
  width: 55px;
}
</style>

